package com.ruoyi.weixin.handler;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.RemoteMasterService;
import com.ruoyi.system.api.domain.WxText;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * 文本消息处理器
 */
@Component
public class TextHandler implements WxMpMessageHandler {

    @Autowired
    private RemoteMasterService remoteMasterService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        // 接收的消息内容
        String inContent = wxMessage.getContent();
        // 响应的消息内容
        String outContent;
        // 根据不同的关键字回复消息，如果命中关键字，则调用远程服务处理任务
        WxText wxText = new WxText(wxMessage.getContent(), wxMessage.getCreateTime(), wxMessage.getMsgType(), wxMessage.getMsgId(), wxMessage.getFromUser());
        AjaxResult ajaxResult = remoteMasterService.weixinTask(wxText, SecurityConstants.INNER);

        if (ajaxResult != null && "200".equals(ajaxResult.get("code").toString())) {
            outContent  = (String) ajaxResult.get("msg");
//            return null;//加入消息队列，默认稍后处理
        } else {
            outContent = "#任务处理失败";
        }
        logger.info("微信文本消息处理结果:"+outContent);
        // 构造响应消息对象
        return WxMpXmlOutMessage.TEXT().content(outContent).fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser()).build();
    }
}
